import org.springframework.beans.factory.BeanFactoryAware
import org.springframework.beans.factory.BeanFactory
import org.springframework.beans.BeansException

class ResourceService implements BeanFactoryAware {

    def indexService
    def beanFactory
    def indexTaskExecutor
    
    void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory
    }
    
    /**
     * closure must return Resource List
     */
    def check(Closure c) {
        def result = c()
        def size = result.size()
        println "resource size = ${size}"
        if (result) {
            println "print out only first 20 entries"
            println "-------------------------------"
            def cnt = Math.min(20, size)
            (0..<cnt).each {
                def resource = result[it]
                println "${resource.id} - ${resource.url}" 
            }
        }
    }
    
    /**
     * closure must return Resource list
     */
    def delete(Closure c) {
        def result = c()
        if (result) {
            def size = result.size()
            println "resource size = ${size}"
            result.each {
                // for each entry
                it.entries.each { entry ->
                    def proc = beanFactory.getBean('removeEntryProcess')
                    proc.entry = entry
                    indexTaskExecutor.execute(proc)
                }
                def id = it.id
                indexTaskExecutor.execute({
                    Resource.get(id).delete()
                })     
            }
        } else {
            println "no resource found"
        }
    }
    
}